#!/usr/bin/python
# -*- coding: utf-8 -*-

import wx
from tvrename import TV
import os

class Controls(wx.Panel):
	def __init__(self, parent, *args, **kwargs):
		wx.Panel.__init__(self, parent, *args, **kwargs)
		self.parent = parent
		self.tvObj = ''
		sizer = wx.GridBagSizer(4, 4)

		PathCap = wx.StaticText(self, label="Path")
		sizer.Add(PathCap, pos=(0, 0), flag=wx.LEFT|wx.TOP, border=10)

		PathTxt = wx.TextCtrl(self)
		sizer.Add(PathTxt, pos=(0, 1), span=(1, 3), flag=wx.TOP|wx.EXPAND, border=5)
		self.PathTxt = PathTxt

		BrowseBtn = wx.Button(self, label="Browse...")
		sizer.Add(BrowseBtn, pos=(0, 4), flag=wx.TOP|wx.RIGHT, border=5)
		BrowseBtn.Bind(wx.EVT_BUTTON, self.OnBrowse)

		ParseBtn = wx.Button(self, label="Parse Dir")
		sizer.Add(ParseBtn, pos=(0, 5), flag=wx.TOP|wx.RIGHT, border=5)
		ParseBtn.Bind(wx.EVT_BUTTON, self.OnParse)

		EpisodesList = wx.ListCtrl(self, style=wx.LC_REPORT, size=(400, 200))
		sizer.Add(EpisodesList, pos=(1, 0), span=(1,6), flag=wx.LEFT|wx.EXPAND)
		EpisodesList.InsertColumn(0, 'Raw Episodes')
		EpisodesList.InsertColumn(1, 'New Titles')
		EpisodesList.SetColumnWidth(0, 200)
		EpisodesList.SetColumnWidth(1, 300)
		self.EpisodesList = EpisodesList

		HelpBtn = wx.Button(self, label='Help')
		sizer.Add(HelpBtn, pos=(2, 0), flag=wx.LEFT|wx.BOTTOM, border=10)
		HelpBtn.Bind(wx.EVT_BUTTON, self.OnHelp)

		RenameBtn = wx.Button(self, label="Rename")
		sizer.Add(RenameBtn, pos=(2, 4))
		RenameBtn.Bind(wx.EVT_BUTTON, self.OnRename)

		ExitBtn = wx.Button(self, label="Exit")
		sizer.Add(ExitBtn, pos=(2, 5), span=(1, 1),  
			flag=wx.BOTTOM|wx.RIGHT, border=5)
		ExitBtn.Bind(wx.EVT_BUTTON, self.OnClose)

		sizer.AddGrowableCol(2)
		self.SetSizer(sizer)

	def OnClose(self, event):
		dlg = wx.MessageDialog(self,
		"Do you really want to close this application?",
		"Confirm Exit", wx.OK|wx.CANCEL|wx.ICON_QUESTION)
		result = dlg.ShowModal()
		dlg.Destroy()
		if result == wx.ID_OK:
			frame = self.GetParent()
			frame.Close()

	def OnBrowse(self, event):
		dlg = wx.DirDialog(self, "Choose a directory:", style=wx.DD_CHANGE_DIR|wx.DD_DIR_MUST_EXIST)
		if dlg.ShowModal() == wx.ID_OK:
			self.PathTxt.SetValue(dlg.GetPath())

	def OnParse(self, event):
		if not self.PathTxt.Value == "":
			self.EpisodesList.DeleteAllItems()
			self.tvObj = TV(self.PathTxt.Value)
			self.APIFunctions()

	def OnRename(self, event):
		try:
			for old, new in self.tvObj.finalTitles.items(): 
				os.rename(old, new)
			wx.MessageBox('{0} File(s) successfully renamed!'.format(len(self.tvObj.finalTitles)), 'Info', wx.OK)
			self.EpisodesList.DeleteAllItems()
			self.tvObj = ''
			del self.tvObj
		except IndexError:
			pass

	def OnHelp(self, event):
		wx.MessageBox("""pytvrenamer v0.01 by Brad Russell and Son Nguyen\n\n
	1. Select the directory which contains your video files either by 
	manually entering the path or by using the "Browse..." button\n
	2. Click the "Parse Dir" button to begin downloading episode info\n
	3. Click the "Rename' when you are ready to rename the files.""",
			 'Help', wx.OK)

	def APIFunctions(self):
		try:
			self.tvObj.GetEpisodes()
			self.tvObj.ParseEpisodes()
			self.tvObj.GetSeriesData()
			self.tvObj.ParseAPI()
			self.tvObj.BuildDictionary()
		except NameError as e:
			wx.MessageBox(str(e),'Error', wx.OK)

		index = 0
		for old, new in self.tvObj.finalTitles.items():
			self.EpisodesList.InsertStringItem(index, old)
			self.EpisodesList.SetStringItem(index, 1, new)
			index += 1	

class MainWindow(wx.Frame):
	"""Main Frame holding the Panel."""
	def __init__(self, *args, **kwargs):
		wx.Frame.__init__(self, *args, **kwargs)
		self.Panel = Controls(self)

if __name__ == '__main__':
	app = wx.App(0)
	frame = MainWindow(None, title="tvrenamer", size=(516, 290), style=wx.CAPTION)
	frame.Show()
	app.MainLoop()